package com.windoent.yugioh.ui.fragment.saishi.ongoing;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.banner.ImageAdapter;
import com.windoent.yugioh.adapter.brvah.multi.JoinGamePlayersMultiAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.GameStatusRoleBean;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.JingWeiBean;
import com.windoent.yugioh.bean.JoinPlayerBean;
import com.windoent.yugioh.bean.SaiShiDetailsBean;
import com.windoent.yugioh.bean.UserBean;
import com.windoent.yugioh.bean.eventbus.FragmentActivityMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.help.map.OpenMapUtil;
import com.windoent.yugioh.help.recycle.GridSpaceItemDecoration;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.meinfo.RealNameAuthActivity;
import com.windoent.yugioh.ui.activity.saishi.ConTestationListActivivty;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.PermissionTool;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.dialog.CanSaiBaoMingXunHuiDetailsDialog;
import com.windoent.yugioh.widget.dialog.ExitGameReasonDialog;
import com.windoent.yugioh.widget.dialog.NotificationOpenDialog;
import com.windoent.yugioh.widget.dialog.PictureVerifyDialog;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/20 11:54
 * desc   :
 */
public class OnGoingDetailsFragment extends BaseFragment {
    private Button mBtnGetCode;
    private Banner mBanner;
    private TextView mTvLocationName;
    private TextView mTvDetailTime;
    private TextView mTvDianpu;
    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mSmartLayout;
    private TextView mTvFormat;
    private TextView mTvCost;
    private TextView mTvPrize;
    private TextView mTvTellphone;
    private TextView mTvRemark;
    private ImageAdapter bannerAdapter;
    private SaiShiDetailsBean.DataBean.InfoBean info;
    private boolean signup = false;
    private JoinGamePlayersMultiAdapter adapter;
    private TextView mTvHuanjing;
    private TextView mTvSaizhi;
    private RelativeLayout mRlRv;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_ongoing_details;
    }

    public static OnGoingDetailsFragment newsInstance(String id) {
        //创建 Bundle
        OnGoingDetailsFragment fragment = new OnGoingDetailsFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        fragment.setArguments(lBundle);
        return fragment;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        mRlRv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ConTestationListActivivty.class);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (signup) {//参赛的
                    String string = MyApplication.getInstance().getUserInfo();
                    if (BaseMethod.notNull(string) && BaseUtils.isJSONValid(string)) {
                        UserBean userBean = gson.fromJson(string, UserBean.class);
                        boolean real = userBean.isReal();
                        if (!real) {//实名
                            showShiMinngDialog();
                        } else {
                            if (info.getIsOnlinePayment() == 1) {
                                //退赛退钱
                                showXunHuiDialog();
                            } else
                                showExitDialog();//退赛
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_nt_join_game));
                }
            }
        });
        mTvLocationName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (info != null) {
                    SaiShiDetailsBean.DataBean.InfoBean.BasicInfoBean basic_info = info.getBasic_info();
                    if (basic_info != null && getActivity() != null) {
                        String address_position = basic_info.getAddress_position();
                        if (BaseUtils.isJSONValid(address_position)) {
                            JingWeiBean json = gson.fromJson(address_position, JingWeiBean.class);
                            if (json != null && BaseMethod.notNull(json.getLatitude()) && BaseMethod.notNull(json.getLongitude())) {
                                OpenMapUtil.openMapPopupWindow(getActivity(), mTvLocationName, basic_info.getAddress(), BaseUtils.stringToDouble(json.getLatitude()), BaseUtils.stringToDouble(json.getLongitude()));
                            } else
                                ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                        } else
                            ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                    } else
                        ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                } else ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
            }
        });
    }

    //巡回赛显示
    private void showXunHuiDialog() {
        CanSaiBaoMingXunHuiDetailsDialog dialog = new CanSaiBaoMingXunHuiDetailsDialog(mContext);
        dialog.setType("4");
        dialog.setYesOnclickListener(new CanSaiBaoMingXunHuiDetailsDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                showPicVerfyDialog();
            }
        });
        dialog.show();
    }

    //图片滑动验证
    private void showPicVerfyDialog() {
        PictureVerifyDialog dialog = new PictureVerifyDialog(mContext);
        dialog.setOnclickListener(new PictureVerifyDialog.onClickListener() {
            @Override
            public void onClick() {

            }
        });
        dialog.show();
    }

    //实名认证
    private void showShiMinngDialog() {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_no_shiming_warn));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setYesStr(getString(R.string.string_to_shiming_renzhen));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                //yes
                Intent intent = new Intent(mContext, RealNameAuthActivity.class);
                intent.putExtra("baoming_details", 1);
                startActivityForResult(intent, Constants.BAOMING_DETAILS);
            }
        });
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.BAOMING_DETAILS && resultCode == Activity.RESULT_OK) {
            showExitDialog();
        }
    }

    //退赛
    private void showExitDialog() {
        ExitGameReasonDialog dialog = new ExitGameReasonDialog(mContext);
        dialog.setOnclickListener(new ExitGameReasonDialog.onClickListener() {
            @Override
            public void onClick(String string) {
                exitGamePlayers(string);
            }
        });
        dialog.show();
    }

    //选手退出参赛
    private void exitGamePlayers(String string) {
        showLoadingDialog("");
        PhoneLive.exitGamePlayers(getUserToken(), id, string, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            signup = false;
                            showBottomBtn(signup);
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_exit_judge_game)), null);
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_caipan_exit_fail), msg);
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }


    //权限通知对话框
    private void showNotificationDialog() {
        NotificationOpenDialog dialog = new NotificationOpenDialog(mContext);
        dialog.setOnclickListener(new NotificationOpenDialog.onClickListener() {
            @Override
            public void onClick() {
                PermissionTool.requestNotify(mContext);
            }
        });
        dialog.show();
    }

    private void initData() {
        initAdapter();
        initBanner();
        showBottomBtn(signup);
    }

    //底部按钮状态
    private void showBottomBtn(boolean signup) {
        mBtnGetCode.setText(signup ? getString(R.string.string_exit_judge_game) : getString(R.string.string_nt_join_game));
    }

    private void initBanner() {
        bannerAdapter = new ImageAdapter(null);
        mBanner.setAdapter(bannerAdapter);
    }

    private void initAdapter() {
        GridLayoutManager manager = new GridLayoutManager(mContext, 12);
        GridSpaceItemDecoration decoration = new GridSpaceItemDecoration(mContext);
        int itemDecorationCount = mRecyclerView.getItemDecorationCount();
        if (itemDecorationCount > 0) {
            mRecyclerView.removeItemDecorationAt(0);
        }
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setLayoutManager(manager);
        adapter = new JoinGamePlayersMultiAdapter();
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mRlRv.onTouchEvent(event);
            }
        });
    }

    private void initView() {
        mBtnGetCode = (Button) mView.findViewById(R.id.btn_get_code);
        mTvLocationName = (TextView) mView.findViewById(R.id.tv_location_name);
        mTvDetailTime = (TextView) mView.findViewById(R.id.tv_detail_time);
        mTvDianpu = (TextView) mView.findViewById(R.id.tv_dianpu);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mBanner = (Banner) mView.findViewById(R.id.banner);

        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mTvFormat = (TextView) mView.findViewById(R.id.tv_format);
        mTvCost = (TextView) mView.findViewById(R.id.tv_cost);
        mTvPrize = (TextView) mView.findViewById(R.id.tv_prize);
        mTvTellphone = (TextView) mView.findViewById(R.id.tv_tellphone);
        mTvRemark = (TextView) mView.findViewById(R.id.tv_remark);

        mTvHuanjing = (TextView) mView.findViewById(R.id.tv_huanjing);
        mTvSaizhi = (TextView) mView.findViewById(R.id.tv_saizhi);
        mRlRv = (RelativeLayout) mView.findViewById(R.id.rl_rv);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事进行中详情tab");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事进行中详情tab");
        }
        getDetailsId();
    }

    private String id;

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            //下拉刷新
            initFresh();
            fresh(id);
        }
    }

    private void initFresh() {
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(id);
            }
        });
    }

    //获取赛事状态角色
    private void getGameStatusRole(String id) {
        showLoadingDialog("");
        PhoneLive.getGameStatusRole(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GameStatusRoleBean json = gson.fromJson(response, GameStatusRoleBean.class);
                            if (json != null) {
                                GameStatusRoleBean.DataBean data = json.getData();
                                if (data != null) {
                                    String role = data.getRole();
                                    int statusid = data.getStatusid();
                                    if (statusid == 8) {
                                        //发送eventbus粘性事件
                                        FragmentActivityMessageEvent event = new FragmentActivityMessageEvent();
                                        event.setMessage(1);
                                        event.setRole(role);
                                        event.setStatusId(statusid);
                                        EventBus.getDefault().postSticky(event);
                                    } else if (statusid != 2 && statusid != 8) {
                                        getDetailsSaiShiData(id);
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //详情
    private void fresh(String id) {
        getGameStatusRole(id);
    }

    private void getDetailsSaiShiData(String id) {
        showLoadingDialog("");
        PhoneLive.getDetailsSaiShiData(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                mSmartLayout.finishRefresh(false);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            mSmartLayout.finishRefresh(true);
                            SaiShiDetailsBean json = gson.fromJson(response, SaiShiDetailsBean.class);
                            SaiShiDetailsBean.DataBean data = json.getData();
                            if (data != null) {
                                info = data.getInfo();
                                signup = data.isSignup();
                                String role = data.getRole();
                                boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
                                boolean playerShenfen = BaseMethod.notNull(role) && role.equals("player");
                                mBtnGetCode.setVisibility(signup && (notJoin || playerShenfen) ? View.VISIBLE : View.GONE);
                                showBottomBtn(signup);
                                if (info != null) {
                                    List<String> banner = info.getBanner();
                                    if (bannerAdapter != null && banner != null && banner.size() > 0) {
                                        mBanner.setVisibility(View.VISIBLE);
                                        bannerAdapter.setDatas(banner);
                                        bannerAdapter.notifyDataSetChanged();
                                    } else {
                                        mBanner.setVisibility(View.GONE);
                                    }
                                    initUi(info);
                                    SaiShiDetailsBean.DataBean.InfoBean.PlayerBean player = info.getPlayer();
                                    if (player != null) {
                                        List<String> player_images = player.getPlayer_images();
                                        String stringCount = BaseMethod.notNullDefaultValueNull(player.getSign_count() + "/" + player.getPlayer_count());
                                        if (player_images != null && player_images.size() > 10) {
                                            List<String> list = player_images.subList(0, 10);
                                            if (adapter != null)
                                                adapter.setNewInstance(getPlayersMulDataBean(list, stringCount));
                                        } else {
                                            if (adapter != null)
                                                adapter.setNewInstance(getPlayersMulDataBean(player_images, stringCount));
                                        }
                                    }
                                }
                            }
                        } else mSmartLayout.finishRefresh(false);
                    } catch (JSONException e) {
                        mSmartLayout.finishRefresh(false);
                        e.printStackTrace();
                    }
                } else {
                    mSmartLayout.finishRefresh(false);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //选手
    private List<JoinPlayerBean> getPlayersMulDataBean(List<String> list, String stringCount) {
        List<JoinPlayerBean> arrayList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            arrayList.clear();
            for (int i = 0; i < list.size(); i++) {
                JoinPlayerBean bean = new JoinPlayerBean();
                bean.setItemType(0);
                bean.setString(list.get(i));
                arrayList.add(bean);
            }
            JoinPlayerBean bean = new JoinPlayerBean();
            bean.setItemType(1);
            bean.setString(stringCount);
            arrayList.add(bean);
        } else {
            arrayList.clear();
            JoinPlayerBean bean = new JoinPlayerBean();
            bean.setItemType(1);
            bean.setString(stringCount);
            arrayList.add(bean);
        }
        return arrayList;
    }

    //刷新ui
    private void initUi(SaiShiDetailsBean.DataBean.InfoBean info) {
        SaiShiDetailsBean.DataBean.InfoBean.BasicInfoBean basic_info = info.getBasic_info();
        SaiShiDetailsBean.DataBean.InfoBean.DescInfoBean desc_info = info.getDesc_info();
        SaiShiDetailsBean.DataBean.InfoBean.PlayerBean player = info.getPlayer();
        if (basic_info != null) {
            setText(mTvLocationName, BaseMethod.notNullDefaultValueNull(basic_info.getAddress_info()));
            setText(mTvDetailTime, BaseMethod.notNullDefaultValueNull(basic_info.getStart_at()));
            setText(mTvDianpu, BaseMethod.notNullDefaultValueNull(basic_info.getCustomer_name()));//主办方
        }
        setText(mTvHuanjing, getConditionName(info.getCondition()));
        setText(mTvFormat, getTypeName(info.getType()));
        if (desc_info != null) {
            setText(mTvSaizhi, BaseMethod.notNullDefaultValueNull(desc_info.getRule_display()));
            setText(mTvCost, BaseMethod.notNullDefaultValueNull(desc_info.getCost() + ""));
            setText(mTvTellphone, BaseMethod.notNullDefaultValueNull(desc_info.getContact()));
            setText(mTvPrize, BaseMethod.notNullDefaultValueNull(desc_info.getPrize_desc()));
            setText(mTvRemark, BaseMethod.notNullDefaultValueNull(desc_info.getRemarks()));
        }
    }

    private String getRuleName(int rule, int round, int wining) {
        //赛制1：瑞士轮 2：淘汰赛 3瑞士轮+淘汰赛 round轮 wining 出几强
        if (BaseMethod.notNull(rule + "") && rule == 1) {
            return getString(R.string.string_game_ruishilun) + round + getString(R.string.string_game_lun);
        }
        if (BaseMethod.notNull(rule + "") && rule == 2) {
            return getString(R.string.string_knock_out);
        }
        if (BaseMethod.notNull(rule + "") && rule == 3) {
            return getString(R.string.string_game_ruishilun) + round + getString(R.string.string_game_lun) + getString(R.string.string_game_chu) + wining + getString(R.string.string_game_qiang);
        }
        return "";
    }

    private String getConditionName(int condition) {
        //比赛环境（1：简体中文赛2：OCG）
        if (BaseMethod.notNull(condition + "") && condition == 1) {
            return getString(R.string.string_chinese_simple_environment);
        }
        if (BaseMethod.notNull(condition + "") && condition == 2) {
            return getString(R.string.string_ocg_environment);
        }
        return "";
    }

    private String getTypeName(int type) {
        //赛事类型 (1:娱乐赛2：积分赛)3：特殊赛4：巡回赛
        if (BaseMethod.notNull(type + "") && type == 1) {
            return getString(R.string.string_entertainment_race);
        }
        if (BaseMethod.notNull(type + "") && type == 2) {
            return getString(R.string.string_point_race);
        }
        if (BaseMethod.notNull(type + "") && type == 3) {
            return getString(R.string.string_teshu_race);
        }
        if (BaseMethod.notNull(type + "") && type == 4) {
            return getString(R.string.string_xunhui_race);
        }
        return "";
    }

}
